from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from app.config.setting import Settings
from databases import Database
from redis.asyncio import Redis
from sqlalchemy import create_engine
from app.config.database import AsyncBase as Base

##############三个数据库的配置
MySQL_database = Database(Settings.database_url) # MySQL
redis_client: Redis = Redis.from_url(Settings.redis_url, decode_responses=True) # Redis
sqlite3_client= Database(Settings.sqlite_url) # sqlite3


def create_tables_SQLite():
    import app.models       # 关键：确保所有模型类在执行前被 Python 加载
    print("准备创建这些表SQLite：", Base.metadata.tables.keys())
    # 用同步驱动创建引擎
    engine = create_engine(f"sqlite:///{Settings.SQLITE_DB_PATH}", echo=True)
    Base.metadata.create_all(bind=engine)

def create_tables_MySQL():
    import app.models       # 关键：确保所有模型类在执行前被 Python 加载
    print("准备创建这些表MySQL：", Base.metadata.tables.keys())
    # 用同步驱动创建引擎
    engine = create_engine(Settings.database_url, echo=True)  # 注意这里要用 MySQL 的 URL
    Base.metadata.create_all(bind=engine)


@asynccontextmanager
async def lifespan(app: FastAPI):#
    import app.models  # 确保模型加载
    print("正在连接数据库与 Redis...")

    # 创建数据库连接
    # await MySQL_database.connect()
    # await sqlite3_client.connect()

    # Redis 初始化连接（ping 确保通）
    # await redis_client.ping()

    # 存入 app.state 共享
    # app.state.mysql_db = MySQL_database
    # app.state.sqlite_db = sqlite3_client
    # app.state.redis = redis_client

    # print("✅ 数据库和 Redis 连接成功")

    """
     try:
        yield
    finally:
        print("📴 正在断开数据库与 Redis...")
        await MySQL_database.disconnect()
        await sqlite3_client.disconnect()
        await redis_client.close()
        print("✅ 清理完成")
    """
    try:
        yield  # ✅ 这是关键，必须要有
    finally:
        print("暂时设置占位")


'''注册路由路径'''
def register_routes(app: FastAPI) -> None:
    from app.api import api_router
    app.include_router(api_router)

def create_app() -> FastAPI:
    app = FastAPI(
        title=Settings.APP_TITLE,
        description=Settings.APP_DESCRIPTION,
        version=Settings.VERSION,
        lifespan=lifespan,
        openapi_url="/openapi.json",
    )
    # 添加中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=Settings.CORS_ORIGINS,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    register_routes(app)
    return app
